package com.yonyou.crm.common.security.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import net.sf.json.JSONObject;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;

public class Md5CodeUtil{
	public static String createMd5CodeForByte(byte[] data) throws CrmMessageException {
		String md5Code = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(data);
	        byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            md5Code = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "MD5生成version信息错误！");
		}
		return md5Code;
	}
	
	public static String createMd5CodeForMap(Map<String, Object> data) throws CrmMessageException {
		if (data == null || data.size() == 0) {
			return "";
		}
		JSONObject obj = JSONObject.fromObject(data);
		return createMd5CodeForByte(obj.toString().getBytes());
	}
	
}